package com.wondertek.poms.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wondertek.oes.sso.common.util.StringUtil;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.vo.GlobalCodeEnum;
import com.wondertek.poms.common.vo.ResultBean;
import com.wondertek.poms.core.config.ContentFormType;
import com.wondertek.poms.core.config.MsgConfig;
import com.wondertek.poms.core.config.SourceConstants;
import com.wondertek.poms.core.service.IAlbumContService;
import com.wondertek.poms.core.service.IImageService;
import com.wondertek.poms.core.service.ISystemConfigService;
import com.wondertek.poms.core.utils.FileIo;
import com.wondertek.poms.core.utils.SyncImageUtil;
import com.wondertek.poms.dao.po.*;
import com.wondertek.poms.dao.po.es.ContentVo;
import com.wondertek.poms.dao.pojo.AlbumContPojo;
import com.wondertek.poms.dao.repo.*;
import com.wondertek.poms.transform.xmlvo.DisplayFileFromXml;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p><b>PcProductRuleServiceImpl Description:</b> 二级产品规则 service层实现 </p>
 *
 * @author 窦再兴
 * <p><b>DATE</b> 2020-10-16 15:56:15</p>
 */
@Slf4j
@Service
@Scope("prototype")
public class AlbumContServiceImpl extends ServiceImpl<AlbumCont, Long> implements IAlbumContService {

	@Autowired
	private IAlbumContDao albumContDao;
	@Autowired
	private IPrdContDao prdContDao;
	@Autowired
	private IPrdInfoDao prdInfoDao;

	@Autowired
	private IContentDao contentDao;
	@Autowired
	private IImageDao imageDao;
	@Autowired
	private IAlbumSalTicketDao albumSalTicketDao;
	@Autowired
	private IClassifyDao classifyDao;
	@Autowired
	private IDisplayFileDao displayFileDao;
	@Autowired
	private IImageService imageService;
	@Autowired
	private ISystemConfigService systemConfigService;

	@Autowired
	private MsgConfig msgConfig;
	@Autowired
	private SourceConstants sourceConstants;

	@Override
	public List<ContentVo> getAlbumContList(Long prdContId) {
		 albumContDao.getAlbumContList(prdContId);
		List<ContentVo> list = new ArrayList<ContentVo>();
		if(prdContId !=null) {
			List<AlbumCont> list1 = albumContDao.getAlbumContList(prdContId);
			if (list1.size() > 0) {
				for (AlbumCont al : list1) {
					if (al.getSubPrdContId() != null) {
						PrdCont prdCont = prdContDao.findByPrdContId(al.getSubPrdContId());
						ContentVo vo = new ContentVo();
						vo.setPrdContId(prdCont.getPrdContId());
						Content content = contentDao.findByContentId(prdCont.getContentId());
						vo.setName(content.getName());
						vo.setContentId(Long.parseLong(prdCont.getContentId()));
						// 排序
						vo.setSort(al.getSort());
						vo.setPublishNoVOMSStatus(StringUtil.null2Str(prdCont.getPublishNoVOMSStatus()));
						list.add(vo);
					}
				}
			}
		}
		return list;
	}

	@Override
	public List<Image> getImageByNodeId(String nodeId,String resType) {
		List<Image> imageList=null;
		if ("content".equals(resType)) {
			Content content = contentDao.findByContentId(nodeId);
			if (content.getContentId() != null) {
				if (content.getImages() != null) {
					String ids=content.getImages();
					if (ids.startsWith(",")) {
						ids = content.getImages().substring(1);
					}
					if (ids.endsWith(",")) {
						ids = content.getImages().substring(0, content.getImages().length() - 1);
					}
					ids=ids.trim().replace(",,", ",");
					try {
						imageList = imageDao.findAllById(StringUtil.stringToLongArray(ids));
					} catch (Exception e) {
						log.error("", e);
					}
				}
			}
		}
		return imageList;
	}

	@Override
	public ResultBean savaAlbumCont(AlbumContPojo albumContPojo) {
		ResultBean resultBean=new ResultBean();
		String tagetContentId = "";
		String target = "";
		String st = albumContPojo.getParams();
		// 排序
		String ss = albumContPojo.getSorts() ;
		String contentId =albumContPojo.getContentId();
		String detail =albumContPojo.getDetail();
		String prdContId =albumContPojo.getPrdContId();
		String shortName =albumContPojo.getShortName();
		String name =albumContPojo.getName();
		String keywords =albumContPojo.getKeywords();
		String displayType =albumContPojo.getDisplayType();
		String prdInfoId =albumContPojo.getPrdInfoId();
		String mtvId =albumContPojo.getMtvId();
		String isMultilingual =albumContPojo.getIsMultilingual();

		if(StringUtil.isNullStr(st)){
			return ResultBean.error(msgConfig.getContentFormType9IsNull());
		}
		String[] params = st.trim().split(",");
		String[] sorts = ss.trim().split(",");
		String recordJson =albumContPojo.getRecordJson();
		String removeJson =albumContPojo.getRemoveJson();
		List<Map> recordMapList =new ArrayList<Map>();
		List<Map> removeMapList =new ArrayList<Map>();
		if(StringUtils.isNotBlank(recordJson) && !"[]".equals(recordJson)){
			recordMapList = JSONArray.parseArray(recordJson, Map.class);
		}
		if(StringUtils.isNotBlank(recordJson) && !"[]".equals(recordJson)){
			removeMapList = JSONArray.parseArray(removeJson, Map.class);
		}
		List<AlbumSalTicket> salTicketList = new ArrayList<AlbumSalTicket>();
		salTicketList = mapList2SalTicketList(recordMapList);
		removeSalTicket(removeMapList, prdContId);

		String selectType =albumContPojo.getSelectType();

		if (StringUtil.isNullStr(contentId)) {
			tagetContentId = albumContDao.initAlbumContentId();
			Content content = new Content();
			content.setShortName(name);
			content.setName(name);
			content.setKeyWords(keywords);
			content.setDisplayType(displayType);
			content.setContentId(tagetContentId);
			content.setMovieLibId(mtvId);
			content.setIsMultilinGual(isMultilingual);
			content.setFormType("9");
			content.setDetail(detail);
			content.setCategory("1");
			content.setType("7");
			content.setContSourceStatus(1L);
			if (!StringUtil.isNullStr(displayType)) {
				Classify classify = classifyDao.findClassifyByClassifyId(displayType);
				if (classify != null) {
					content.setDisplayName(classify.getClassifyName());
				}
			}
			content.setStatus(Long.valueOf("0"));
			Content.putTimeAndUser(content);
			content.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			content.setLastModifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			content.setAssetId(tagetContentId);
			contentDao.save(content);
			boolean flag = true;
			if (!"1".equals(selectType)) {
				PrdInfo prdInfo=prdInfoDao.findByPrdInfoId(Long.valueOf(prdInfoId));
				PrdCont prdCont = new PrdCont(content, prdInfo);
				prdContDao.save(prdCont);
				if (salTicketList != null && salTicketList.size() > 0) {
					for (AlbumSalTicket albumSalTicket : salTicketList) {
						albumSalTicket.setAlbumId(prdCont.getPrdContId());
						albumSalTicketDao.save(albumSalTicket);
					}
				}

				for (int i = 0; i < params.length; i++) {
					String key = params[i];
					int sort = StringUtil.stringToInteger(sorts[i]);
					if (!StringUtil.isNullStr(key)) {
						AlbumCont albumCont = new AlbumCont();
						albumCont.setAlbumId(prdCont.getPrdContId());
						albumCont.setSubPrdContId(Long.valueOf(key));
						albumCont.setPrdInfoId(Long.valueOf(prdInfoId));
						albumCont.setAlbumContId(tagetContentId);
						albumCont.setSubContId(prdCont.getContentId());
						albumCont.setSort(sort);
						albumContDao.save(albumCont);

						PrdCont prd =prdContDao.findByPrdContId(Long.valueOf(key));
						if (prd != null) {
							if ((prdInfo.getAutoVomsPublish() == 1 && prd.getPublishNoVOMSStatus() == null)
									||  22!=prd.getPublishNoVOMSStatus()) {
								prd.setPublishNoVOMSStatus(10);
								prdContDao.save(prd);
							}
						}
					}
				}
				saveAndDel(tagetContentId, "1111",albumContPojo.getRecordToSave());
				if (StringUtils.isNotBlank(target)) {
					resultBean.setMsg(msgConfig.getAlbumContPrdContExistMessage());
					resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
				} else {
					resultBean.setMsg("保存成功");
					resultBean.setCode(GlobalCodeEnum.SUCCESS.getCode());
				}
			} else if ("1".equals(selectType)) {
				List<Content> list = new ArrayList<Content>();
				list.add(content);
				contentDao.deleteAll(list);
				resultBean.setMsg(msgConfig.getAlbumContFilterPrdInfoIsNotNull());
				resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
			} else {
				List<Content> list = new ArrayList<Content>();
				list.add(content);
				contentDao.deleteAll(list);
				resultBean.setMsg(msgConfig.getSaveFail());
				resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
			}
		}

		if (!StringUtil.isNullStr(contentId)) {
			List<AlbumCont> li = albumContDao.getAlbumContList(Long.valueOf(prdContId));
			if (!StringUtil.isNullStr(prdContId)) {
				if (salTicketList != null && salTicketList.size() > 0) {
					for (AlbumSalTicket albumSalTicket : salTicketList) {
						albumSalTicket.setAlbumId(StringUtil
								.nullToLong(prdContId));
						albumSalTicketDao.save(albumSalTicket);
					}
				}
			}

			List<String> list = new ArrayList<String>();
			if (li != null && li.size() > 0) {
				for (AlbumCont album : li) {
					list.add(album.getSubPrdContId().toString());
				}
			}

			Content content =contentDao.findByContentId(contentId);
			if (content.getId() != null
					&& !"".equals(content.getId().toString().trim())) {
				content.setName(name);
				content.setShortName(name);
				content.setDetail(detail);
				content.setKeyWords(keywords);
				content.setDisplayType(displayType);
				content.setMovieLibId(mtvId);
				content.setIsMultilinGual(isMultilingual);
				if (!StringUtil.isNullStr(displayType)) {
					Classify classify = classifyDao.findClassifyByClassifyId(displayType);
					if (classify != null) {
						content.setDisplayName(classify.getClassifyName());
					}
				}
				content.setShortName(shortName);
				contentDao.save(content);
				for (int i = 0; i < params.length; i++) {
					String key = params[i];
					int sort = StringUtil.stringToInteger(sorts[i]);
					if (!StringUtil.isNullStr(key)) {
						list.remove(key);
						// Boolean flag = false;
						AlbumCont oldAc = this.albumContDao.findAlbumContByAlbumContIdAndSubPrdContId(prdContId,Long.parseLong(key));
						if (/*tag == false &&*/ oldAc == null) {
							PrdCont prd = prdContDao.findByPrdContId(Long.valueOf(key));
							AlbumCont albumCont = new AlbumCont();
							albumCont.setAlbumId(Long.valueOf(prdContId));
							albumCont.setAlbumContId(contentId);
							albumCont.setPrdInfoId(Long.valueOf(prdInfoId));
							albumCont.setSubPrdContId(Long.valueOf(key));
							albumCont.setSubContId(prd==null?null:prd.getContentId());
							albumCont.setSort(sort);
							albumContDao.save(albumCont);
							if (prd != null) {
								PrdInfo prdInfo =prdInfoDao.findByPrdInfoId(prd.getPrdInfoId());
								if ((prdInfo.getAutoVomsPublish() == 1 && prd.getPublishNoVOMSStatus() == null)
									  || 22!=prd.getPublishNoVOMSStatus()) {
									prd.setPublishNoVOMSStatus(10);
									prdContDao.save(prd);
								}
							}
						}
						// 更新排序
						if (oldAc != null) {
							oldAc.setSort(sort);
							albumContDao.save(oldAc);
						}
					}
				}
				if (list.size() > 0) {
					for (String s : list) {
						for (AlbumCont album : li) {
							if (album.getSubPrdContId().toString().equals(s)) {
								if (albumContDao.findAlbumContByAlbumContId(album.getId().toString())!=null) {
									albumContDao.deleteById(album.getId());
									PrdCont prd = prdContDao.findByPrdContId(album.getSubPrdContId());
									PrdInfo prdInfo = prdInfoDao.findByPrdInfoId(prd.getPrdInfoId());
									if (prd != null) {
										if ((prdInfo.getAutoVomsPublish() == 1 && prd
												.getPublishNoVOMSStatus() == null)
												|| (prd.getPublishNoVOMSStatus() != null && prd
												.getPublishNoVOMSStatus() != 22)) {
											prd.setPublishNoVOMSStatus(10);
											prdContDao.save(prd);
										}
									}
								}
							}
						}
					}
				}
			}
			resultBean=saveAndDel(contentId, "1111",albumContPojo.getRecordToSave());
			PrdCont albumPrdCont =prdContDao.findByPrdContId(Long.valueOf(prdContId));
			if (albumPrdCont != null
					&& albumPrdCont.getPublishNoVOMSStatus() != null
					&& albumPrdCont.getPublishNoVOMSStatus() == 12) {
				albumPrdCont.setPublishNoVOMSStatus(10);
				prdContDao.save(albumPrdCont);
			}
			if (StringUtils.isNotBlank(target)) {
				resultBean.setMsg(msgConfig.getAlbumContPrdContExistMessage()+":"+target);
				resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
			} else {
				resultBean.setCode(GlobalCodeEnum.SUCCESS.getCode());
			}
		}
		return resultBean;
	}

	public ResultBean saveAndDel(String nodeId, String resType,List<Image>  recordToSave) {
		ResultBean resultBean=new ResultBean();
		boolean result = false;
		if (nodeId == null || "".equals(nodeId) || resType == null || "".equals(resType)) {
			resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
			resultBean.setMsg(msgConfig.getImageSaveAndDelDataError() );
			return resultBean;
		}
		List<Image> saveMap = recordToSave;
//		try {
//			saveMap = JSONArray.parseArray(recordToSave, Image.class);
//		} catch (Exception e) {
//			log.error(e.toString());
//			resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
//			resultBean.setMsg(msgConfig.getImageSaveAndDelDataException() );
//			return resultBean;
//		}
		try {
			List<Image> saveImages = new ArrayList<Image>();
			if (saveMap != null) {
				for (int i = 0; i < saveMap.size(); i++) {
					Image img = imageService.createImage(saveMap.get(i));
					String tags = img.getTags();
					String tempName = img.getName();
					if (tempName.indexOf("H32_sc") > 0 || tempName.indexOf("V23_sc") > 0 || tempName.indexOf("V34_sc") > 0 || tempName.indexOf("H169_sc") > 0) {

					} else {
						if (tags.equals("head")) {
							tempName += "_H32_sc";
						} else if (tags.equals("small")) {
							tempName += "_V23_sc";
						} else if (tags.equals("big")) {
							tempName += "_V34_sc";
						} else {
							tempName += "_H169_sc";
						}
					}
					img.setName(tempName);
					saveImages.add(img);
					if (img.getFileType() == null || "".equals(img.getFileType())) {
						resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
						resultBean.setMsg(msgConfig.getImageSaveAndDelDataException());
						return resultBean;
					}
				}
			}
			Content c = contentDao.findByContentId(nodeId.toString());
			imageService.saveAndDelContImage(c, saveImages);
			List<DisplayFile> dfs = displayFileDao.findAllByContentId(c.getContentId());
			List<DisplayFileFromXml> displayFileList = new ArrayList<DisplayFileFromXml>();
			if (c.getDisplayFileList() != null && c.getDisplayFileList().size() > 0) {
				for (DisplayFile df : dfs) {
					DisplayFileFromXml fromXml = new DisplayFileFromXml();
					BeanUtils.copyProperties(df, fromXml);
					displayFileList.add(fromXml);
				}
			}
			c.setDisplayFileList(displayFileList);
			//播单生成逻辑同专辑生成逻辑，这里直接使用专辑生成逻辑的方法
			genMetadataXml(c);

		} catch (Exception e) {
			log.error("", e);
			resultBean.setCode(GlobalCodeEnum.FAILURE.getCode());
			resultBean.setMsg(msgConfig.getImageSaveAndDelDataException());
			return resultBean;
		}
		return ResultBean.ok();
	}

	public void genMetadataXml(Content content) throws Exception {
		String contentId = content.getContentId();
		String contentFormType = content.getFormType();
		log.info("==生成 " + ContentFormType.getBykey(contentFormType) + contentId + " 原始数据文件 开始==");
		String basePath = getMetadataRoot(contentId);
		String origFilePath = basePath + "Metadata.xml";
		//生成Metadata.xml
		Map<String, Object> root = new HashMap<String, Object>();
		root.put("Version", "1.0.0");
		root.put("AssetID", content.getAssetId());
		root.put("ContentID", content.getContentId());
		root.put("Name", content.getName());
		root.put("ShortName", content.getShortName());
		root.put("CreateTime", content.getCreateTime());
		root.put("ModifyTime", content.getLastModifyTime());
		root.put("CreatorID", content.getCreatorId());
		root.put("Detail", content.getDetail());
		root.put("Type", content.getType());
		root.put("Category", content.getCategory());
		root.put("FormType", content.getFormType());
		root.put("DisplayName", content.getDisplayName());
		root.put("DisplayType", content.getDisplayType());
		root.put("MTV_ID", content.getMovieLibId());
		List<Map<String, String>> dpList = new LinkedList<Map<String, String>>();
		if(content.getDisplayFileList() != null && content.getDisplayFileList().size()>0) {
			for(int i=0; i<content.getDisplayFileList().size(); i++) {
				DisplayFileFromXml df = content.getDisplayFileList().get(i);
				Map<String, String> displayFile = new HashMap<String, String>();

				displayFile.put("DpFileID", df.getDpFileId());
				displayFile.put("DpFileName", df.getDpFileName());
				displayFile.put("DpFileDetail", df.getDpFileDetail());
				displayFile.put("DpFileType", df.getDpFileType());
				displayFile.put("DpUsageCode", df.getDpUsageCode());
				displayFile.put("DpUseType", df.getDpUseType());
				displayFile.put("DpAdapType", df.getDpAdapType());
				displayFile.put("Pixel", df.getDpPixel());

				dpList.add(displayFile);
			}
		}
		root.put("DisplayFileLists", dpList);

		List<Map<String, String>> kwList = new LinkedList<Map<String, String>>();
		if(content.getKeyWords() != null && !content.getKeyWords().equals("")) {
			String kwss = content.getKeyWords().replaceAll("，", ",");
			String[] kws = kwss.split(",");
			if(kws.length>0) {
				for(String kw:kws) {
					Map<String, String> kwm = new HashMap<String, String>();

					kwm.put("KeywordName", kw);
					kwm.put("PrimaryKey", "0");

					kwList.add(kwm);
				}
			}
		}
		root.put("Keywords", kwList);
		String tmpPath = sourceConstants.getDepository() + File.separator + "album"
				+ File.separator + content.getContentId() + "-" + System.currentTimeMillis() + ".xml";
		File localFile = new File(tmpPath);
		if (!localFile.getParentFile().exists()) {
			localFile.getParentFile().mkdirs();
		}

		Map<String, Object> metaMap = new HashMap<String, Object>();
		metaMap.put("CONTENT", root);
		Configuration cfg = new Configuration();
		cfg.setDefaultEncoding("utf-8");
		cfg.setEncoding(Locale.getDefault(), "utf-8");
		cfg.setStrictSyntaxMode(true);
		cfg.setNumberFormat("0");
		cfg.setClassForTemplateLoading(AlbumContServiceImpl.class, "/");
		try {
			Template template = cfg.getTemplate("/template/albumMetadata.ftl");
			FileWriter out = new FileWriter(localFile);
			template.process(metaMap, out);
			out.close();
			Thread.sleep(200);
			FileIo.fileCopy(tmpPath, origFilePath, true);
		} catch (IOException | TemplateException e) {
			throw new Exception(e);
		}

		if(localFile.exists()) {
			localFile.delete();
		}

		//拷贝图片
		String imgPath = basePath + "display" + File.separator;

		String pubImgPath = systemConfigService.findAllBykey("PUBLISH_IMAGE_BASE_PATH")==null?"":systemConfigService.findAllBykey("PUBLISH_IMAGE_BASE_PATH").getValue();
		if("".equals(pubImgPath)) {
			log.info("==发布节目nas地址PUBLISH_IMAGE_BASE_PATH未配置==");
			return;
		}
		String[] dp = pubImgPath.split(",");
		String cPath = "/" + contentId.substring(0, 4) + "/" + contentId.substring(4, 7)
				+ "/" + contentId.substring(7, 10) + "/";
		File s = new File(imgPath);
		if(s.exists() && s.isDirectory()) {
			File[] fs = s.listFiles();
			if(fs != null && fs.length > 0) {
				for(File img : fs) {
					log.debug("==内容[" + contentId + " 拷贝文件[" + img.getName() + "==");
					for(String p : dp) {
						if(!StringUtil.isNullStr(p)) {
							FileIo.fileCopy(img.getAbsolutePath(), p + cPath + img.getName(), true);
						}
					}
				}
				basePath = getMetadataRootNew(contentId);
				transformImage(content, basePath, content.getDisplayFileList());
			}else {
				log.error("==内容[" + contentId + " 图片为空==");
			}
		}
		log.info("==生成 " + ContentFormType.getBykey(contentFormType) + contentId + " 原始数据文件 结束==");
	}

	public void transformImage(Content content, String basePath, List<DisplayFileFromXml> displayFileList) {
		String tempPath = getSourcePhotoBasePath(content.getContentId(),basePath);	// /zhengshi/4/3/3/10/display/
		String sourceBasepath = sourceConstants.getSyncFileBasePath();	// /usr/local/syncContent + tempPath
		String destFolderPath = getDestBasePath(tempPath);	// /nas/nas_source/display/zhengshi/4/3/3/10/display


		System.out.println(tempPath);
		System.out.println(sourceBasepath);
		System.out.println(destFolderPath);
		System.out.println(displayFileList.size());
		System.out.println(displayFileList.toString());
//		DisplayFile dfHSJ720H = null;
		List<DisplayFileFromXml> pImages = new ArrayList<DisplayFileFromXml>();

		//sc
		String oldDisplaySourceFileName = sourceConstants.getDisplaySourceFileName();
		String displaySourceFileName = oldDisplaySourceFileName;
		String swh = systemConfigService.findAllBykey("NEW_ENCODE_IMAGE_SWITCH").getValue();
		boolean bNewEncode = false;
		if(swh != null && swh.length()>0 && swh.trim().equals("on")) {
			bNewEncode = true;
			//H32_sc
			displaySourceFileName = sourceConstants.getDisplaySourceFileNameNew();
		}

		//格式化更新时间
		String curDate = "";
		try {
			String lastModifyTime = content.getLastModifyTime();
			if(lastModifyTime == null || lastModifyTime.equals("")) {
				content.setLastModifyTime(content.getCreateTime());//yyyy-MM-dd HH:mm:ss
			}else {
				if(lastModifyTime.indexOf("-") == -1) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					content.setLastModifyTime(sdf2.format(sdf.parse(lastModifyTime)));
				}
			}

			//时间戳
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			curDate =  sdf.format(sdf2.parse(content.getLastModifyTime()));
			log.info("=====时间戳:" + curDate + "==, content.getLastModifyTime=" + content.getLastModifyTime());
		} catch (Exception ex) {
			log.error("内容[" + content.getContentId() + "最后更新时间修改格式失败", ex);
		}


		//新发布流程
		Map<String, String> newPubImgPathMap = new HashMap<String, String>();
		String contentId = content.getContentId();
		try {
			///poms_publish/cmvideo/image,/poms_publish_end/cmvideo/image,/nas/bak_poms3/cmvideo/image
			String baseImgPath = systemConfigService.findAllBykey("PUBLISH_IMAGE_BASE_PATH").getValue();
			if(baseImgPath != null && baseImgPath.length() > 1) {
				String cPath = "/" + contentId.substring(0, 4) + "/" + contentId.substring(4, 7)
						+ "/" + contentId.substring(7, 10) + "/";
				String[] dp = baseImgPath.split(",");
				for(int i = 0; i<dp.length; i++) {
					String p = dp[i];
					if(!StringUtil.isNullStr(p)) {
						newPubImgPathMap.put("newPublish"+i, p + cPath);
					}
				}
			}else {
				log.info("==发布节目nas地址PUBLISH_IMAGE_BASE_PATH未配置==");
			}
		} catch (Exception e1) {
			log.error("新发布 路径错误",e1);
		}

		Map<String, Integer> keepImgs = new HashMap<String, Integer>();
		boolean allSuc = true;
		if (displayFileList != null && displayFileList.size() > 0) {
			Iterator<DisplayFileFromXml> iteratorDisplayFile = displayFileList.iterator();
			while (iteratorDisplayFile.hasNext()) {

				DisplayFileFromXml displayFile = iteratorDisplayFile.next();
				String sourceName = displayFile.getDpFileName();
				String sourceFile = sourceBasepath + sourceName;	//  /usr/local/syncContent/zhengshi/4/3/3/10/display
				FileIo.fileCopy(sourceFile, destFolderPath + sourceName, true);	//[/usr/local/syncContent/zhengshi/4/3/3/10/display---> /nas/nas_source/display/zhengshi/4/3/3/10/display]

				//拷贝到新nas上
//				try {
//					shuntDisplay(SyncConstants.syncConfig.displayFileShuntMap,sourceFile, tempPath + sourceName);	//根据配置批量复制图片, 由于存储已停用，此处不再执行(20170310)
//
//					if(!newPubImgPathMap.isEmpty()) {
//						shuntDisplay(newPubImgPathMap,sourceFile, sourceName);
//					}
//				} catch (Exception e1) {
//					log.error("新发布 拷贝原图片出错",e1);
//				}

				keepImgs.put(sourceName, 1);
				if(bNewEncode) {
					if(sourceName.indexOf("V34_sc")>-1 || sourceName.indexOf("V23_sc")>-1 || sourceName.indexOf("H32_sc")>-1 || sourceName.indexOf("H169_sc")>-1) {
						if(sourceName.indexOf("V34_sc")>-1) {
							String webp_filename;
							log.info("=====转图片之前的时间:======"+ curDate );
							//yyyymmddhhmm_TV_CONTENT.jpg
							webp_filename = curDate + "_" + "TV_CONTENT.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + webp_filename, "jpg", 320, 240,
									newPubImgPathMap, tempPath, webp_filename);
							keepImgs.put(webp_filename, 1);

							//yyyymmddhhmm_FILENAME_V34_720.webp
							webp_filename = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_V34_sc")) + "_V34_720.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + webp_filename, "webp", 320, 240,
									newPubImgPathMap, tempPath, webp_filename);
							keepImgs.put(webp_filename, 1);

							//yyyymmddhhmm_V_CONTENT.jpg
							webp_filename = curDate + "_" + "V_CONTENT.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + webp_filename, "jpg", 176, 132,
									newPubImgPathMap, tempPath, webp_filename);
							keepImgs.put(webp_filename, 1);

							//yyyymmddhhmm_FILENAME_HSJ1080V.jpg
							String tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_V34_sc")) + "_HSJ1080V.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "jpg", 440, 330,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_V34_1080.webp
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_V34_sc")) + "_V34_1080.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 440, 330,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);
						}
						if(sourceName.indexOf("V23_sc")>-1) {
							//yyyymmddhhmm_FILENAME_V23_1080.webp	330x495
							String tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_V23_sc")) + "_V23_1080.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 495, 330,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_HSJ720V.jpg
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_V23_sc")) + "_HSJ720V.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "jpg", 330, 220,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_V23_720.webp
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_V23_sc")) + "_V23_720.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 330, 220,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);
						}
						if(sourceName.indexOf("H32_sc")>-1) {
							//yyyymmddhhmm_FILENAME_HSJ1080H.jpg
							String tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H32_sc")) + "_HSJ1080H.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "jpg", 339, 508,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_H32_1080.webp
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H32_sc")) + "_H32_1080.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 339, 508,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_HSJ720H.jpg
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H32_sc")) + "_HSJ720H.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "jpg", 224, 336,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_H32_720.webp
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H32_sc")) + "_H32_720.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 224, 336,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							DisplayFileFromXml dfHSJ720H = new DisplayFileFromXml();
							dfHSJ720H.setContentId(content.getContentId());
							dfHSJ720H.setDpAdapType(displayFile.getDpAdapType());
							dfHSJ720H.setDpFileDetail(displayFile.getDpFileDetail());
							dfHSJ720H.setDpFileId("");
							dfHSJ720H.setDpFileName(tmpName);
							String dpFilePath = StringUtil.null2Str(displayFile.getDpFilePath());
							dfHSJ720H.setDpFilePath(dpFilePath.replace(sourceName, tmpName));
							dfHSJ720H.setDpFileType(displayFile.getDpFileType());
							dfHSJ720H.setDpPixel("");
							dfHSJ720H.setDpUsageCode(displayFile.getDpUsageCode());
							dfHSJ720H.setDpUseType(displayFile.getDpUseType());

							pImages.add(dfHSJ720H);
						}
						if(sourceName.indexOf("H169_sc")>-1) {
							//yyyymmddhhmm_FILENAME_H169_1080.jpg
							String tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H169_sc")) + "_H169_1080.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "jpg", 324, 576,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_H169_1080.webp
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H169_sc")) + "_H169_1080.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 324, 576,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_H169_720.jpg
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H169_sc")) + "_H169_720.jpg";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "jpg", 189, 336,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);

							//yyyymmddhhmm_FILENAME_H169_720.webp
							tmpName = curDate + "_" + sourceName.substring(0, sourceName.indexOf("_H169_sc")) + "_H169_720.webp";
							changeSizeAndCopy(sourceFile, destFolderPath, destFolderPath + tmpName, "webp", 189, 336,
									newPubImgPathMap, tempPath, tmpName);
							keepImgs.put(tmpName, 1);
							DisplayFileFromXml dfHSJ720H = new DisplayFileFromXml();
							dfHSJ720H.setContentId(content.getContentId());
							dfHSJ720H.setDpAdapType(displayFile.getDpAdapType());
							dfHSJ720H.setDpFileDetail(displayFile.getDpFileDetail());
							dfHSJ720H.setDpFileId("");
							dfHSJ720H.setDpFileName(tmpName);
							String dpFilePath = StringUtil.null2Str(displayFile.getDpFilePath());
							dfHSJ720H.setDpFilePath(dpFilePath.replace(sourceName, tmpName));
							dfHSJ720H.setDpFileType(displayFile.getDpFileType());
							dfHSJ720H.setDpPixel("");
							dfHSJ720H.setDpUsageCode(displayFile.getDpUsageCode());
							dfHSJ720H.setDpUseType(displayFile.getDpUseType());
							pImages.add(dfHSJ720H);
						}
					}
				}
				//兼容老的图片转码  当配图二次加工开关打开，但用户只发了_sc，未发H32_sc，仍保留老的转码方式
				String ucode = displayFile.getDpUsageCode();
				if(bNewEncode && sourceName.indexOf(oldDisplaySourceFileName) != -1 && !ucode.equals("96") && !ucode.equals("97")
						&& !ucode.equals("98") && sourceName.indexOf("JZ_sc") == -1 && sourceName.indexOf("HB_sc") == -1
						&& sourceName.indexOf("BZ_sc") == -1) {
					log.info("'" + sourceName + "' is old image encode");

					displaySourceFileName = oldDisplaySourceFileName;
				}
			}
		}
		log.info("内容[" + content.getContentId() + " 图片二次转码结果为"+allSuc);
		if(pImages.size() > 0) {
			content.getDisplayFileList().addAll(pImages);
		}
		File omsDir = new File(destFolderPath); // /nas/nas_source/display/zhengshi/4/3/3/10/display
		log.info("内容[" + content.getContentId() + " nas_source地址：" + destFolderPath);
		if(omsDir.exists() && omsDir.isDirectory()) {
			File[] fs = omsDir.listFiles();
			if(fs != null && fs.length > 0) {
				for(File f : fs) {
					if(f.isFile()) {
						f.delete();
					}
				}
			}
		}
		//记录转码时间
		content.setLastTranscodeTime(curDate);
		contentDao.save(content);
	}
	private void changeSizeAndCopy(String _tmpSourceFilePath, String _destFoderPath, String _destFilePath, String _fileType,
								   int _height, int _width, Map<String, String> _pubNewFilePathMap, String _tempOldFilePath, String _pubFileName) {
		// change size
		boolean isSuc = false;
		System.out.println("_tmpSourceFilePath:"+_tmpSourceFilePath+"__destFoderPath:"+_destFoderPath+"_destFilePath:"+_destFilePath+"+_fileType:"+
				_fileType+"__height:"+_height+"__width:"+_width+"__pubNewFilePathMap:"+ JSON.toJSON(_pubNewFilePathMap)+"__tempOldFilePath:"+_tempOldFilePath+
				"__pubFileName:"+_pubFileName);
		try {
			isSuc = SyncImageUtil.scaleImage(_tmpSourceFilePath, _destFilePath, _width, _height, true, _fileType, _destFoderPath);
		} catch (Exception e) {
			log.error("改变图片大小失败", e);
		}
		// copy to publish path
		if (isSuc) {
			try {
				try {
					//拷贝到新nas上
					if(!_pubNewFilePathMap.isEmpty()) {
						shuntDisplay(_pubNewFilePathMap, _destFilePath, _pubFileName);
					}
				} catch (Exception e) {
					log.error("新发布 拷贝转换图片出错",e);
				}
				log.debug("syncMessage:copyImage to "+ _destFilePath + " Success!");
			} catch (Exception e) {
				log.error("syncMessage:copyImage to "+ _destFilePath + " Fail!", e);
			}
		} else {
			log.error("!syncError:parseImage:" + _tmpSourceFilePath + " Fail!");
		}
	}
	private String getSourcePhotoBasePath(String contentId, String basePath) {
		StringBuffer path = new StringBuffer("");
		path.append("/");
		path.append(basePath);
		path.append("/");
		path.append(contentId);
		path.append("/");
		path.append(sourceConstants.getDisplayFilePath());
		path.append("/");
		return path.toString();
	}

	private void shuntDisplay(Map<String, String> shuntMap,String source, String destPath) {
		if (shuntMap != null) {
			Set<String> set = shuntMap.keySet();
			if (set != null) {
				Iterator<String> iterator = set.iterator();
				while (iterator.hasNext()) {
					String key = iterator.next();
					String path = shuntMap.get(key);
					//如果设置了排除文件，则不复制
					boolean isExclude=false;
					//怎么迁移  优化没想到  整个业务
//					String excludeNames = StringUtils.trimToEmpty(SyncConstants.syncConfig.displayFileExcludeMap.get(key));
//					if(StringUtils.isNotBlank(excludeNames) ){
//						String[] e=excludeNames.split(",");
//						if(null != e && e.length>0){
//							for(String n:e){
//								String fName=(path+destPath).substring((path + destPath).lastIndexOf("_"));
//								if(fName.equals(n)){
//									log.info("shuntDisplay matched exclude filename "+n+" and skip to copy file "+fName +" to DEST "+key);
//									isExclude=true;
//									break;
//								}
//							}
//						}
//					}

					log.info("拷贝图片到" + path);
					try {
						if(!isExclude){
							FileIo.fileCopy(source, path + destPath,true);
						}
					} catch (Exception e) {
						log.info("拷贝图片到[" + path+destPath + "时出错！");
						e.printStackTrace();
					}
				}
			}
		}
	}

	private String getDestBasePath(String tempPath) {
		StringBuffer path = new StringBuffer(sourceConstants.getDisplayBasePath());
		path.append(tempPath);
		return path.toString();
	}

	private String getMetadataRootNew(String contId) {
		StringBuilder path = new StringBuilder();
		path.append(contId.substring(0, 4));
		path.append(File.separator);
		path.append(contId.substring(4, 7));
		path.append(File.separator);
		path.append(contId.substring(7));
		return  "zhengshi" + File.separator + path.toString();
	}

	private String getMetadataRoot(String contId) {
		StringBuilder path = new StringBuilder();
		if (contId == null) {
			return null;
		}
		String orgId = contId;
		if (contId.length() < 10) {
			int length = contId.length();
			for (int i = 0; i < (10 - length); i++) {
				contId = "0" + contId;
			}

		}
		path.append(contId.substring(0, 4));
		path.append(File.separator);
		path.append(contId.substring(4, 7));
		path.append(File.separator);
		path.append(contId.substring(7));
		String metadataRoot = sourceConstants.getSyncFileBasePath();
		return metadataRoot + File.separator + "zhengshi" + File.separator + path.toString() + File.separator + orgId
				+ File.separator;
	}

	private List<AlbumSalTicket> mapList2SalTicketList(List<Map> recordMapList) {
		List<AlbumSalTicket> salTicketList = new ArrayList<AlbumSalTicket>();
			AlbumSalTicket albumSalTicket = null;
			for (Map map : recordMapList) {
				albumSalTicket = new AlbumSalTicket();
				if (!StringUtil.isNullStr(map.get("salTicketId"))) {
					albumSalTicket.setSalTicketId(StringUtil.nullToLong(map
							.get("salTicketId")));
				}
				if (!StringUtil.isNullStr(map.get("cooperatorId"))) {
					albumSalTicket.setCooperatorId(StringUtil.nullToLong(map
							.get("cooperatorId")));
				}
				if (!StringUtil.isNullStr(map.get("salTicketPrice"))) {
					albumSalTicket.setSalTicketPrice(StringUtil.null2Str(map
							.get("salTicketPrice")));
				}
				if (!StringUtil.isNullStr(map.get("salStartTime"))) {
					albumSalTicket.setSalStartTime(StringUtil.null2Str(map
							.get("salStartTime")));
				}
				if (!StringUtil.isNullStr(map.get("salEndTime"))) {
					albumSalTicket.setSalEndTime(StringUtil.null2Str(map
							.get("salEndTime")));
				}
				if (!StringUtil.isNullStr(map.get("onOrOff"))) {
					albumSalTicket.setOnOrOff(StringUtil.nullToInteger(map
							.get("onOrOff")));
				}
				salTicketList.add(albumSalTicket);
			}
		return salTicketList;
	}

	private void removeSalTicket(List<Map> removeMapList, String albumId) {
		List<AlbumSalTicket> list =albumSalTicketDao.getAlbumSalTicketsByAlbumId(Long.parseLong(albumId));
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				boolean flag = false;
				Long id = list.get(i).getId();
				for (Map map : removeMapList) {
					if (id.equals(StringUtil.nullToLong(map.get("id")))) {
						AlbumSalTicket albumSalTicket = list.get(i);
						albumSalTicket.setOnOrOff(StringUtil.nullToInteger(map
								.get("onOrOff")));
						albumSalTicketDao.save(albumSalTicket);
						flag = true;
					}
				}
				if (!flag) {
					albumSalTicketDao.deleteById(id);
				}
			}
		}
	}

	@Override
	public AlbumCont deleteLogic(Long id) {
		albumContDao.deleteById(id);
		return null;
	}

	@Override
	public AlbumCont merge(AlbumCont model) {
		albumContDao.save(model);
		return null;
	}
}